#ifndef CLIENTTHREAD_H
#define CLIENTTHREAD_H

#include <QThread>
#include <QMutex>
#include <QFile>
#include <QMessageBox>
#include <QTime>
#include <QHttpRequestHeader>
#include <QCoreApplication>
#include <QWaitCondition>
#include "virtualfsobject.h"



class QDsSocket;
class QTcpSocket;
class Server;


class ClientThread : public QThread
{
    Q_OBJECT
public:
    ClientThread(Server *s, int descriptor);
    ~ClientThread();

    QString ip();
    QTcpSocket *socket();
    void run();
    void waitForFinished();
    void abort();
    void force_abort();
    void dialog();


    inline quint64 totalUploaded() {
        return total_uploaded;
    }

    inline quint64 totalDownloaded() {
        return total_downloaded;
    }

    inline quint64 currentUploadSpeed() {
        return current_upload_speed;
    }

    inline quint64 currentDownloadSpeed() {
        return current_download_speed;
    }


    inline void setDownloadingObject(const QString & f) {
        downloading = f;
    }


    QString downloadingObject() {
        return downloading;
    }

    static void disconnected_thread(ClientThread *th);


signals:
    void clientThreadCreated( ClientThread * );
    void clientThreadDestroyed( ClientThread * );
    void txRxSizeRefreshed(int tx, int rx);

    void exitThread();
    void closeSocket();
    void socketDisconnectFromHost();


private:
    QString request_location(const QString & head);
    int prepareAnsverData(const QString & head, QString & ansver, VirtualFsObject **vfs_obj, int *fd);


public slots:
    void close_socket();
    void transferData();
    void clientConnected();
    void clientDisconnected();
    void thread_finished();

    void socket_ready_read();
    void socket_disconnected();
    void socket_bytes_write();
    void socket_bytes_written(qint64 bytes);


private:
    QMutex mtx;
    QWaitCondition wait_cond;
    QMutex finish_mutex;
    Server *serv;
    QTcpSocket *_socket;
    bool force_exit;
    int descriptor, disconnect_emited, disconnecting;
    QString _ip;
    QHttpRequestHeader _header;

    quint64 current_upload_speed;
    quint64 current_download_speed;

    quint64 total_uploaded;
    quint64 total_downloaded;

    QString downloading;


    struct {
        VirtualFsObject *fs_obj;
        QTime time;
        QByteArray send_data;
        int file_fd;
        qint64 _sz, last_size, part_size, uploaded;
    }transfer;
};

#endif // CLIENTTHREAD_H
